//
//  YSGResetPasswordController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/4/21.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class YSGResetPasswordController: UITableViewController {
    
    var handlerClosure: (() -> Void)?
    
    private var model = RegisterModel() {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        model.titles = ["手机号", "验证码", "登录密码", "确认密码", "确认"]
        setupNavBar()
        setupUI()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return model.numberOfRows
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = RegisterFormCell.init()
        let cellType = RegisterFormCellType(rawValue: indexPath.row + 4) ?? .phone
        cell.configure(with: model, cellType: cellType, type: .forget)
        cell.delegate = self
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellType = RegisterFormCellType(rawValue: indexPath.row + 4) ?? .phone
        switch cellType {
        case .register: return 110
        default: return 50
        }
    }
}

extension YSGResetPasswordController: RegisterFormCellDelegate {
    func register(didSendSmsCode cell: RegisterFormCell) {
        model.sendSmsCode(success: {
            HUDTool.show(message: "短信发送成功")
        }) { errorMsg in
            cell.resetCodeBtn()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func register(_ cell: RegisterFormCell, didEndEditing model: RegisterModel) {
        switch cell.cellType {
        case .phone:
            if model.phone.isEmpty {
                HUDTool.show(message: "手机号不能为空")
            } else if !model.phone.isPhone() {
                HUDTool.show(message: "手机号格式错误")
            }
        default: break
        }
        self.model = model
    }
    
    func register(didStartRegister cell: RegisterFormCell) {
        if model.phone.isEmpty {
            HUDTool.show(message: "请填写手机号")
            return
        }
        
        if model.code.isEmpty {
            HUDTool.show(message: "请输入验证码")
            return
        }
        
        if model.password.isEmpty {
            HUDTool.show(message: "请设置登录密码")
            return
        }
        
        if model.repassword.isEmpty {
            HUDTool.show(message: "请确认登录密码")
            return
        }
        
        if model.password != model.repassword {
            HUDTool.show(message: "登录密码两次输入不一样")
            return
        }
        
        resetPassword()
    }
    
    private func resetPassword() {
        let phone = model.phone.encryptWithAES()
        let password = model.password.encryptWithAES()
        HUDTool.showActivity()
        RegisterModel.forgetPassword(phone: phone,
                                     code: model.code,
                                     password: password)
        { (errorMsg, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                UserDefaults.savePassword(password)
                self.handlerClosure?()
                self.navigationController?.dismiss(animated: true)
            }
        }
    }
}

extension YSGResetPasswordController {
    private func setupNavBar() {
        title = "忘记密码"
        let leftItem = UIBarButtonItem(imageName: "nav_back", target: self, action: #selector(dismissTo))
        navigationItem.leftBarButtonItem = leftItem
    }
    
    private func setupUI() {
        tableView.backgroundColor = .white
        tableView.keyboardDismissMode = .onDrag
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.tableFooterView = UIView()
        
        tableView.register(RegisterFormCell.self, forCellReuseIdentifier: RegisterFormCell.reuseIdentifier)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tap.cancelsTouchesInView = false
        tableView.addGestureRecognizer(tap)
    }
    
    @objc private func dismissKeyboard() {
        tableView.endEditing(true)
    }
    
    @objc private func dismissTo() {
        dismiss(animated: true)
    }
}
